Example: Using Draggable Markers with Barikoi React GL
The Marker
component in the react-bkoi-gl
package enables users to place and drag markers on the map. This interactive feature allows users to reposition markers by dragging them, providing a dynamic way to update locations. Ideal for applications requiring flexible marker placement, the Marker
component enhances user interaction and map customization.
Example
"use client";
import { useRef } from 'react';
import { Map, Marker } from 'react-bkoi-gl'; // Import the Barikoi React GL package
import "react-bkoi-gl/styles" // Import CSS for proper map styling
const App = () => {
const BARIKOI_API_KEY = 'YOUR_BARIKOI_API_KEY_HERE'
const mapStyle = `https://map.barikoi.com/styles/osm-liberty/style.json?key=${BARIKOI_API_KEY}`
const mapContainer = useRef(null);
const mapRef = useRef(null);
const initialViewState = {
longitude: 90.36402,
latitude: 23.823731,
minZoom: 4,
maxZoom: 30,
zoom: 13,
bearing: 0,
pitch: 0,
antialias: true
}
const [marker, setMarker] = useState({
latitude: initialViewState.latitude,
longitude: initialViewState.longitude
});
const [events, logEvents] = useState({});
// On marker drag
const onMarkerDrag = useCallback((event) => {
logEvents(_events => ({..._events, onDrag: event.lngLat}));
setMarker({
longitude: event.lngLat.lng,
latitude: event.lngLat.lat
});
}, []);
// On marker drag start
const onMarkerDragStart = useCallback((event) => {
logEvents(_events => ({..._events, onDragStart: event.lngLat}));
}, []);
// On marker drag end
const onMarkerDragEnd = useCallback((event) => {
logEvents(_events => ({..._events, onDragEnd: event.lngLat}));
}, []);
return (
<div
ref={mapContainer} style={containerStyles}
>
<Map
ref={mapRef}
mapStyle={mapStyle}
style={{ width: "100%", height: "100%" }}
initialViewState={initialViewState}
doubleClickZoom={false}
dragRotate={false}
attributionControl={false}
>
<Marker
longitude={marker.longitude}
latitude={marker.latitude}
anchor="bottom"
draggable
onDragStart={onMarkerDragStart}
onDrag={onMarkerDrag}
onDragEnd={onMarkerDragEnd}
>
<img src="./pin.png" />
</Marker>
</Map>
</div>
)
}
// JSX Styles
const containerStyles = {
width: "100%",
height: "100vh",
minHeight: "400px",
overflow: "hidden",
}
export default App